package com.jcli.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class KeyValuePairsGUI extends JFrame {
    private DefaultListModel<String> listModel;
    private JList<String> keyList;
    private JButton deleteButton;

    public KeyValuePairsGUI() {
        setTitle("Key-Value Pairs");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建一个 DefaultListModel 来存储键值对
        listModel = new DefaultListModel<>();

        // 创建一个 JList 来显示键值对
        keyList = new JList<>(listModel);

        // 创建一个滚动面板以容纳 JList
        JScrollPane scrollPane = new JScrollPane(keyList);

        // 创建一个删除按钮
        deleteButton = new JButton("删除所有键值对");

        // 将删除按钮添加到窗口
        add(deleteButton, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);

        // 为删除按钮添加点击事件处理程序
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int option = JOptionPane.showConfirmDialog(null,
                        "您确定要删除所有键值对吗？", "确认删除", JOptionPane.YES_NO_OPTION);

                if (option == JOptionPane.YES_OPTION) {
                    // 用户确认删除，清空键值对
                    listModel.clear();
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                KeyValuePairsGUI gui = new KeyValuePairsGUI();
                gui.setVisible(true);
            }
        });
    }
}
